package GoodsService

import (
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/response"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

func GetGoodsActivityGoodsList(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	activityId := r.GetInt64("activity_id")
	keyWord := r.GetString("keyWord", "")
	categoryId := r.GetInt("category_id", 0)
	if activityId == 0 {
		return response.FailByRequestMessage(r, "活动id不能为空")
	}
	ctx := r.Context()
	where := g.Map{
		"g.id IN (SELECT goods_id FROM gd_goods_activity_goods_list WHERE delete_at<1 AND activity_id = ?)": activityId,
	}
	if len(keyWord) > 0 {
		where["(g.goods_name LIKE ? OR g.sub_title LIKE ? OR g.short_title LIKE ?)"] = []interface{}{"%" + keyWord + "%", "%" + keyWord + "%", "%" + keyWord + "%"}
	}
	if categoryId > 0 {
		where["g.cates LIKE ?"] = "%," + gconv.String(categoryId) + ",%"
	}
	pager, err := GetPager(ctx, where, req.Page, req.PageSize, "")
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	// 找出goodsids
	goodsIds := []int64{}
	for _, v := range pager.List {
		goodsIds = append(goodsIds, gconv.Int64(v.Id))
	}

	// 处理已设置的规格
	res, err := GetActivityOptionByActivityIdGoodsIds(ctx, activityId, goodsIds)
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	// 组装 GoodsOption，借用的
	for _, v := range pager.List {
		for _, v2 := range res {
			if v2.GaglId < 1 {
				continue
			}
			if gconv.Int64(v.Id) == v2.GoodsId {
				v.ActivityGoods = append(v.ActivityGoods, v2)
			}
		}
	}

	return response.SuccessByRequestMessageData(r, "成功", pager)
}
